'use strict';

// 该文件为原始router文件

const koaRouter = require('koa-router');
const join = require('path').join;
const run = require('./run');
const methods = require('methods').concat('all');

module.exports = class Router {
  constructor (configure) {
    methods.forEach(method => {
      const self = this;
      this[method] = function (path, actionAndoptions) {
        actionAndoptions = Array.from(arguments).slice(1);
        self[method][path] = [].concat(actionAndoptions);
      };
    });
    this.use = (path, subRouter) => {
      if (typeof subRouter === 'function') {
        const sub = new Router(subRouter);
        this.use[path] = sub;
      } else {
        this.use[path] = subRouter;
      }
    };
    if (typeof configure === 'function') {
      configure(this);
    }
  }

  get _routes() {
    const signs = Object.keys(this)
      .filter(method => method !== 'use')
      .map(method => Object.keys(this[method]).map(path => [method, path]))
      .reduce((a, b) => a.concat(b), []);
    let routes = signs.map(sign => sign.concat(this[sign[0]][sign[1]]));

    const subPaths = Object.keys(this.use);
    const subRoutes = subPaths.map(path => this.use[path]._routes.map(sub => {
      sub[1] = join(path, sub[1]);
      return sub;
    })).reduce((a, b)=>a.concat(b), []);

    routes = routes.concat(subRoutes);
    return routes;
  }

  forKoa() {
    const router = new koaRouter();
    const routes = this._routes;
    routes.forEach(route => {
      const method = route[0];
      const path = route[1];
      const actionsAndOptions = route.slice(2);
      const actions = actionsAndOptions.filter(i => typeof i === 'function');
      const options = actions.length < actionsAndOptions.length ? actionsAndOptions[actions.length] : null;
      const action = actions.pop();
      router[method].apply(router, [].concat(path, actions, run(action, options)));
      // router[method](path,run(action, options));
    });
    return router;
  }
};
